<template>
  <el-form class="query-container" ref="queryFormRef" :model="queryParams" :inline="true" @submit.native.prevent>
    <el-form-item label="账号" prop="username">
      <el-input
          v-model="queryParams.username"
          placeholder="请输入账号"
          clearable
          @keyup.enter.native="handleQuery"
      />
    </el-form-item>
    <el-form-item label="昵称" prop="name">
      <el-input
          v-model="queryParams.name"
          placeholder="请输入昵称"
          clearable
          @keyup.enter.native="handleQuery"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleQuery">搜索</el-button>
      <el-button @click="resetQuery">重置</el-button>
    </el-form-item>
  </el-form>

  <div class="inner-container">
    <el-row :gutter="10" style="margin-bottom:8px">
      <el-col :span="1.5" v-if="$hasPermission('crm:system:user:add')">
        <el-button type="primary" plain @click="showAddDialog">新增</el-button>
      </el-col>
      <el-col :span="1.5" v-if="$hasPermission('crm:system:user:updata')">
        <el-button type="success" plain @click="showEditDialog" :disabled="selectedIds.length!==1">修改</el-button>
      </el-col>
      <el-col :span="1.5" v-if="$hasPermission('crm:system:user:del')">
        <el-button type="danger" plain @click="handleDelete(null)" :disabled="!selectedIds.length">删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button type="warning" plain @click="handleExport">导出</el-button>
      </el-col>-->
    </el-row>

    <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50"/>
      <el-table-column label="头像">
        <template #default="scope">
          <el-avatar :src="scope.row.avatar" :size="32"/>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="账号"/>
      <el-table-column prop="name" label="昵称"/>
      <el-table-column prop="email" label="邮箱" show-overflow-tooltip/>
      <el-table-column prop="phone" label="手机" show-overflow-tooltip/>
      <el-table-column prop="sex" label="性别" :formatter="sexFormatter">
<!--        <template #default="scope">
          <span v-if="scope.row.sex === 0">男</span>
          <span v-else-if="scope.row.sex === 1">女</span>
          <span v-else-if="scope.row.sex === 2">未知</span>
        </template>-->
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" type="success">正常</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="info">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip/>
      <el-table-column label="操作" fixed="right" width="150">
        <template #default="scope">
          <el-button type="primary" link icon="Edit" @click="showEditDialog(scope.row)" v-if="$hasPermission('crm:system:user:updata')">修改</el-button>
          <el-dropdown>
            <el-button type="primary" link>更多
              <el-icon><arrow-down/></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleDelete(scope.row)" v-if="$hasPermission('crm:system:user:del')">删除</el-dropdown-item>
                <el-dropdown-item @click="resetPassword(scope.row)" v-if="$hasPermission('crm:system:user:reset')">重置密码</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <br>
    <el-pagination
        :total="total"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" :before-close="closeDialog" append-to-body>
      <el-form ref="dialogFormRef" :model="formData" :rules="formRules" label-width="50px">
        <template v-if="formData.id === undefined">
          <el-form-item label="账号" prop="username">
            <el-input v-model="formData.username" placeholder="请输入账号"/>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="formData.password" placeholder="默认请留空" type="password" show-password/>
          </el-form-item>
        </template>
        <el-form-item label="昵称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入昵称"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机"/>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select style="width:100%" clearable v-model="formData.sex" placeholder="请选择性别">
            <el-option label="男" :value="0"/>
            <el-option label="女" :value="1"/>
            <el-option label="未知" :value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select style="width:100%" clearable multiple v-model="formData.roleIds" placeholder="请选择角色">
            <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer class="dialog-footer">
        <el-button type="primary" @click="saveOrUpdate">确定</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import request from '@/utils/request'

// --------------------------------------------------
const loading = ref(false)
const queryFormRef = ref()
const queryParams = ref({pageNum: 1, pageSize: 10})
const total = ref(0)
const tableData = ref([])
const selectedIds = ref([])

const listData = () => {
  loading.value = true
  request.get('/api/sys/users/select', {
    params: queryParams.value
  }).then(res => {
    total.value = res.data.total
    tableData.value = res.data.list
    loading.value = false
  })
}

const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

const handleQuery = () => {
  queryParams.value.pageNum = 1
  listData()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  listData()
}

const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  listData()
}

const handleDelete = (row) => {
  let ids = row ? [row.id] : [...selectedIds.value]
  if (ids.length === 0) {
    ElMessage.error('请选择要删除的记录')
    return
  }
  ElMessageBox.confirm('确定删除吗？', '提示', {
    type: 'warning'
  }).then(() => {
    request.delete(`/api/sys/users/delete?ids=${ids}`)
        .then(res => {
          selectedIds.value.length = 0
          listData()
          ElMessage.success('删除成功')
        })
  }).catch(() => {})
}

/*const handleExport = () => {
  ElMessageBox.confirm('确定导出吗？', '提示', {
    type: 'warning'
  }).then(() => {
    request.downloadExcel('/api/sys/users/export', queryParams.value)
  }).catch(() => {})
}*/

const handleStatus = (row) => {
  request.patch(`/api/sys/users/${row.id}/status?status=${row.status}`)
      .then(res => {
        ElMessage.success('操作成功')
      })
}

const resetPassword = (row) => {
  ElMessageBox.confirm('确定重置密码吗？', '提示', {
    type: 'warning'
  }).then(() => {
    request.patch(`/api/sys/users/${row.id}/resetPassword`)
        .then(res => {
          ElMessage.success('重置密码成功')
        })
  }).catch(() => {})
}

// --------------------------------------------------
const dialogTitle = ref('')
const dialogVisible = ref(false)
const dialogFormRef = ref()
const formData = ref({
  id: undefined,
  username: undefined,
  password: undefined,
  name: undefined,
  type: 0,
  email: undefined,
  phone: undefined,
  sex: 0,
  avatar: undefined,
  status: 0,
  roleIds: []
})
const formRules = ref({
  username: [
    {required: true, message: '账号为必填项'}
  ],
  password: [
    {min: 6, max: 30, message: '长度在 6 到 30 个字符'}
  ],
  name: [
    {required: true, message: '昵称为必填项'},
    {min: 2, max: 30, message: '长度在 2 到 30 个字符'}
  ],
  phone: [
    {pattern: /^1[3-9]\d{9}$/, message: '手机格式错误'}
  ],
  email: [
    {pattern: /^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/, message: '邮箱格式错误'}
  ],
  roleIds: [
    {required: true, message: '角色为必选项'}
  ]
})

const showAddDialog = () => {
  getRoleList()
  dialogTitle.value = '新增用户'
  dialogVisible.value = true
}

const showEditDialog = (row) => {
  let id = row.id || selectedIds.value
  request.get(`/api/sys/users/updata/select/${id}`)
      .then(res => {
        formData.value = {
          ...res.data,
          sex: Number(res.data.sex)
        }

        getRoleList()
        dialogTitle.value = '修改用户'
        dialogVisible.value = true
      })
}

const closeDialog = () => {
  formData.value = {
    id: undefined,
    username: undefined,
    password: undefined,
    name: undefined,
    type: 0,
    email: undefined,
    phone: undefined,
    sex: 0,
    avatar: undefined,
    status: 0,
    roleIds: []
  }
  dialogFormRef.value.resetFields()
  dialogVisible.value = false
}

const saveOrUpdate = () => {
  dialogFormRef.value.validate(valid => {
    if (!valid) {
      ElMessage.error('请正确填写参数')
      return
    }
    const id = formData.value.id
    request({
      url: '/api/sys/users/save',
      method: 'post',
      data: formData.value
    }).then(res => {
      closeDialog()
      listData()
      ElMessage.success(id ? '修改成功' : '新增成功')
    });
  })
}

const roleList = ref([])

const getRoleList = () => {
  request.get('/api/sys/roles/all')
      .then(res => {
        roleList.value = res.data
      })
}

// --------------------------------------------------
const sexArr = ref([]);
const  sexFormatter = (row,column,cellValue,index)=>{
  if(!sexArr.value){
    return cellValue;
  }
  for(let item of sexArr.value){
    if(item.value == cellValue){
      cellValue = item.label;
    }
  }
  return cellValue;
}

onMounted(() => {
  loadDictOptions(sexArr,'user_sex');
  listData()
})
</script>

<style scoped>

</style>
